<template>
  <div class="rich-text">
    <div id='quillEditorQiniu'>
      <!-- 基于elementUi的上传组件 el-upload begin-->
      <el-upload
          class="avatar-uploader"
          :accept="'image/*'"
          :show-file-list="false"
          :http-request="uploadFile"
          :on-success="uploadEditorSuccess"
          :on-error="uploadEditorError"
          :before-upload="beforeEditorUpload">
      </el-upload>
      <!-- 基于elementUi的上传组件 el-upload end-->
      <quill-editor
      v-show="mixEditable"
        ref="customQuillEditor"
        class="editor"
        v-model="value"
        :options="editorOption" 
        @ready="onEditorReady($event)" 
        @blur="onEditorBlur($event)"
        @focus="onEditorFocus($event)"
        @change="onEditorChange($event)"
      >
      </quill-editor>
      <div v-if="!mixEditable" v-html="value" style="height: 300px; border: 1px solid #ccc;overflow-y: auto;padding: 0 10px;">

      </div>
    </div>

  </div>

</template>

<script>
//引入quill-editor编辑器
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
//实现quill-editor编辑器拖拽上传图片
import * as Quill from 'quill'
import { ImageDrop } from 'quill-image-drop-module'
import emoji from 'node-emoji'
import { loadRoute3Path } from '@/utils/loadRemote'
import quillEmoji from 'quill-emoji'
import 'quill-emoji/dist/quill-emoji.css'
import './editor.css'
//实现quill-editor编辑器调整图片尺寸
// // 这里引入修改过的video模块并注册
// import Video from "@/components/quillEditor/quillVideo";
// Quill.register(Video, true)

// import ImageResize from 'quill-image-resize-module'
// Quill.register('modules/imageResize', ImageResize)
Quill.register('modules/quillEmoji', quillEmoji)
Quill.register('modules/ImageDrop', ImageDrop)
Vue.prototype.emoji = emoji


//自定义编辑器的工作条
// import {getToken} from "@/utils/auth";
// toolbar标题
const titleConfig = [
  { Choice: '.ql-insertMetric', title: '跳转配置' },
  { Choice: '.ql-bold', title: '加粗' },
  { Choice: '.ql-italic', title: '斜体' },
  { Choice: '.ql-underline', title: '下划线' },
  { Choice: '.ql-header', title: '段落格式' },
  { Choice: '.ql-strike', title: '删除线' },
  { Choice: '.ql-blockquote', title: '块引用' },
  { Choice: '.ql-code', title: '插入代码' },
  { Choice: '.ql-code-block', title: '插入代码段' },
  { Choice: '.ql-font', title: '字体' },
  { Choice: '.ql-size', title: '字体大小' },
  { Choice: '.ql-list[value="ordered"]', title: '有序列表' },
  { Choice: '.ql-list[value="bullet"]', title: '无序列表' },
  { Choice: '.ql-direction', title: '文本方向' },
  { Choice: '.ql-header[value="1"]', title: 'h1' },
  { Choice: '.ql-header[value="2"]', title: 'h2' },
  { Choice: '.ql-align', title: '对齐方式' },
  { Choice: '.ql-color', title: '字体颜色' },
  { Choice: '.ql-background', title: '背景颜色' },
  { Choice: '.ql-image', title: '图像' },
  { Choice: '.ql-video', title: '视频' },
  { Choice: '.ql-link', title: '添加链接' },
  { Choice: '.ql-formula', title: '插入公式' },
  { Choice: '.ql-clean', title: '清除字体格式' },
  { Choice: '.ql-emoji', title: '表情包' },
  { Choice: '.ql-script[value="sub"]', title: '下标' },
  { Choice: '.ql-script[value="super"]', title: '上标' },
  { Choice: '.ql-indent[value="-1"]', title: '向左缩进' },
  { Choice: '.ql-indent[value="+1"]', title: '向右缩进' },
  { Choice: '.ql-header .ql-picker-label', title: '标题大小' },
  { Choice: '.ql-header .ql-picker-item[data-value="1"]', title: '标题一' },
  { Choice: '.ql-header .ql-picker-item[data-value="2"]', title: '标题二' },
  { Choice: '.ql-header .ql-picker-item[data-value="3"]', title: '标题三' },
  { Choice: '.ql-header .ql-picker-item[data-value="4"]', title: '标题四' },
  { Choice: '.ql-header .ql-picker-item[data-value="5"]', title: '标题五' },
  { Choice: '.ql-header .ql-picker-item[data-value="6"]', title: '标题六' },
  { Choice: '.ql-header .ql-picker-item:last-child', title: '标准' },
  { Choice: '.ql-size .ql-picker-item[data-value="small"]', title: '小号' },
  { Choice: '.ql-size .ql-picker-item[data-value="large"]', title: '大号' },
  { Choice: '.ql-size .ql-picker-item[data-value="huge"]', title: '超大号' },
  { Choice: '.ql-size .ql-picker-item:nth-child(2)', title: '标准' },
  { Choice: '.ql-align .ql-picker-item:first-child', title: '居左对齐' },
  { Choice: '.ql-align .ql-picker-item[data-value="center"]', title: '居中对齐' },
  { Choice: '.ql-align .ql-picker-item[data-value="justify"]', title: '两端对齐' },
  // { Choice: '.ql-table', title: '插入表格' },
  // { Choice: '.ql-table-insert-row', title: '插入行' },
  // { Choice: '.ql-table-insert-column', title: '插入列' },
  // { Choice: '.ql-table-delete-row', title: '删除行' },
  // { Choice: '.ql-table-delete-column', title: '删除列' },
]
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
  ['blockquote', 'code-block'], // 引用  代码块
  [{ header: 1 }, { header: 2 }], // 1、2 级标题
  [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
  [{ script: 'sub' }, { script: 'super' }], // 上标/下标
  [{ indent: '-1' }, { indent: '+1' }], // 缩进
  [{ direction: 'rtl' }], // 文本方向
  [{ size: ['small', false, 'large', 'huge'] }], // 字体大小
  [{ header: [1, 2, 3, 4, 5, 6] }], // 标题
  [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
  [{ font: ['songti'] }], // 字体种类
  [{ align: [] }], // 对齐方式
  // [
    // {'table': 'TD'},
    // {'table-insert-row': 'TIR'},
    // {'table-insert-column': 'TIC'},
    // {'table-delete-row': 'TDR'},
    // {'table-delete-column': 'TDC'}
  // ],
  ['image'], // 链接、图片、视频
  ['emoji'],//表情包
  ['clean'], // 清除文本格式
]

export default {
  name: "rich-Editor",
  components: {
    quillEditor,
     ImageDrop
  },
  props: {
    value: {},
    mode: {
      default: "edit", // 编辑模式和 edit， 展示模式 view
    },
    groupId: {
      default: '1'
    }
  },
  data() {
    return {
      headers: {
        // Authorization: "Bearer " + getToken(),
      },
      uploadImgUrl:"/v1/admin/common/upload",
      uploadUrlPath:"没有文件上传",
      quillUpdateImg:false,
      content:'<p>example contentqw<span class="ql-emojiblot" data-name="grinning">﻿<span contenteditable="false"><span class="ap ap-grinning">😀</span></span>﻿</span></p>',    //最终保存的内容
      editorOption:{
        placeholder: this.$attrs.placeholder,
        modules: {
          'emoji-toolbar': true,
          "emoji-textarea": false,
          'emoji-shortname': true,
          // imageResize: {
          //   displayStyles: {
          //     backgroundColor: 'black',
          //     border: 'none',
          //     color: 'white'
          //   },
          //   modules: [ 'Resize', 'DisplaySize', 'Toolbar' ]
          // },
          toolbar: {
            container: toolbarOptions,  // 工具栏
            table: true, // 设为true
            handlers: {
              'image': function (value) {
                if (value) {
                  document.querySelector('#quillEditorQiniu .avatar-uploader input').click()
                } else {
                  this.quill.format('image', false);
                }
              },
            }
          },
        }
      },
      imageHeight: '30px'
    }   
  },
  computed: {
    dispatchProxy(){
      if (Vue.prototype.dispatchProxy) {
        return Vue.prototype.dispatchProxy(this)
      } else {
        return this.dispatch
      }
    },
    mixEditable() {
      return !(this.$attrs.readonly || this.$attrs.disabled) && this.mode === "edit"
    },
  },
  watch: {
    value: {
      immediate: true,
      handler(newVal) {
        //this.$emit('input', newVal);
      console.log(newVal,'===value')
      }
    }
  },
  created() {
  },
  mounted() {
    // this.onEditorReady()
  },
  methods: {
    onEditorReady(quill) {
      // console.log('editor ready!', quill);
      for (let item of titleConfig) {
        let tip = document.querySelector('.quill-editor ' + item.Choice)
        if (!tip) continue
        tip.setAttribute('title', item.title)
      }
    },
    onEditorBlur(quill) {
      // console.log('onEditorBlur!', quill);
    },
    onEditorFocus(quill) {
      // console.log('onEditorFocus!', quill);
    },
    onEditorChange(quill) {
      this.$emit('input', this.value)
      // console.log('onEditorChange!', quill);
    },
    //上传图片之前async
    beforeEditorUpload(res, file){
      //显示上传动画
      // this.quillUpdateImg = true;
      //  const res1 = await uploadImage()
      // console.log(res1,'=====');
      // this.$emit('before',res, file)
      // console.log(res);
      // console.log(file);
      return true
    },
    async uploadFile(file) {
      console.log(file,'SourceMaterialController')
      const importLoading = this.$loading({
        lock: true,
        text: '导入中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.4)',
      })
      let params = new FormData()
        params.append('multipartFile', file.file)
        params.append('types', 'image')
        params.append('imageName', file.file.name)
        params.append('materialGroupId', this.groupId)
        params.append('isUpdate', 'update')
        params.append('iconType', 'notIcon')
      params.append('version', '1')
      const resp = await this.dispatchProxy(Vue.prototype.Controllers.SourceMaterialController.uploadMaterial, {
        payload: params,
      })
      console.log(resp.data[0],'===resp')
      if (!resp.error) {
        let prefixUrl = loadRoute3Path('')
        const {code} = resp.data[0]
        const image = `<img src="${prefixUrl}/api/afc/materials/font/actions/show?code=${code}&iconType=notIcon&types=image" alt="加载失败">`
        this.$emit('input', (this.value || '') + image)
        this.$message.success('上传成功!')
      } else {
        this.$message.warning('请去素材库的图片管理获取对应的分组id')
      }
      importLoading.close()
    },
    // 上传图片成功
    async uploadEditorSuccess(res, file) {
      console.log(res, file,'====上传成功')
    },
    // 上传(文件)图片失败
    uploadEditorError(res, file) {
      console.log(res, file,'====上传成功')
      //页面提示
      // this.$message.error('上传图片失败')
      // //取消上传动画
      // this.quillUpdateImg = false;
    },
    //上传组件返回的结果
    uploadResult:function (res){
      this.uploadUrlPath=res;
    },
    openContent:function (){
      console.log(this.content,'====openContent')
    },

  },
};
</script>
<style lang="scss" scoped>
.rich-text {
  width: 100%;
}

.editor {
  line-height: normal !important;
  height: 300px;
  margin-bottom: 50px;
}
.ql-snow .ql-tooltip[data-mode="link"]::before {
  content: "请输入链接地址:";
}
.ql-snow .ql-tooltip.ql-editing a.ql-action::after {
  border-right: 0px;
  content: "保存";
  padding-right: 0px;
}

.ql-snow .ql-tooltip[data-mode="video"]::before {
  content: "请输入视频地址:";
}
.ql-snow .ql-picker.ql-size .ql-picker-label::before,
.ql-snow .ql-picker.ql-size .ql-picker-item::before {
  content: "14px";
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="small"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="small"]::before {
  content: "10px";
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="large"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="large"]::before {
  content: "18px";
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="huge"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="huge"]::before {
  content: "32px";
}

.ql-snow .ql-picker.ql-header .ql-picker-label::before,
.ql-snow .ql-picker.ql-header .ql-picker-item::before {
  content: "文本";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="1"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="1"]::before {
  content: "标题1";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="2"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="2"]::before {
  content: "标题2";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="3"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="3"]::before {
  content: "标题3";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="4"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="4"]::before {
  content: "标题4";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="5"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="5"]::before {
  content: "标题5";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="6"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="6"]::before {
  content: "标题6";
}

.ql-snow .ql-picker.ql-font .ql-picker-label::before,
.ql-snow .ql-picker.ql-font .ql-picker-item::before {
  content: "标准字体";
}
.ql-snow .ql-picker.ql-font .ql-picker-label[data-value="serif"]::before,
.ql-snow .ql-picker.ql-font .ql-picker-item[data-value="serif"]::before {
  content: "衬线字体";
}
.ql-snow .ql-picker.ql-font .ql-picker-label[data-value="monospace"]::before,
.ql-snow .ql-picker.ql-font .ql-picker-item[data-value="monospace"]::before {
  content: "等宽字体";
}


/*加上height和滚动属性就可以，滚动条样式是系统默认样式，可能不同*/
.ql-toolbar.ql-snow .ql-picker.ql-expanded .ql-picker-options {
  border-color: #ccc;
  height: 125px;
  overflow: auto;
}
::v-deep.textarea-emoji-control {
  display: none !important;
}

</style>
